package it.mp.multitask;

import java.util.List;

import it.mp.multitask.factory.PreferenceFactory;
import it.mp.multitask.utility.PatternEntry;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;

public class Setup extends PreferenceActivity {
	public static final String PREFIX_PREFERRED_APPS = "P_";
	public static final String PREFIX_DONT_SHOW_APPS = "";
	public static final String DELIMITER = "##";
	private static final String SERIALIZABLE_TASK = "SERIALIZABLE_TASK";
	PreferenceScreen listDontShowAppScreen;
	PreferenceScreen listPreferredAppScreen;
	private OnPreferenceChangeListener opclPreferedApps = new OnPreferenceChangeListener() {

		public boolean onPreferenceChange(Preference cbox, Object valore) {
			boolean addPreferito = (Boolean) valore;
			String lista = Setup.this.getPreferenceManager().getSharedPreferences().getString(
					Setup.this.getResources().getString(R.string.Apps_list_preferred), ";");
			if (addPreferito) {
				lista += ";" + cbox.getKey();
			} else {
				lista.replace(";" + cbox.getKey(), "");
			}
			Editor editor = Setup.this.getPreferenceManager().getSharedPreferences().edit();
			editor.putString(Setup.this.getResources().getString(R.string.Apps_list_preferred), lista);
			editor.commit();
			return true;
		}

	};

	private Handler messageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case (AsyncGetInstalledApps.FINISH_OK) :
					pd.dismiss();
					break;
				case (AsyncGetInstalledApps.FINISH_KO) :
					pd.dismiss();
					break;
			}
		}
	};
	private ProgressDialog pd;
	private AsyncGetInstalledApps task;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);

		int standardLayout = Integer.parseInt(getPreferenceManager().getSharedPreferences().getString(this.getResources().getString(R.string.theme_main_new),
				"0"));
		PreferenceFactory.getStyle(standardLayout, this).crea();

		findPreference(getResources().getString(R.string.theme_main_new)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

			public boolean onPreferenceChange(Preference arg0, Object arg1) {

				PreferenceFactory.getStyle((Integer.parseInt((String) arg1)), Setup.this).crea();
				return true;
			}

		});

		ListPreference listBackgroundGlobal = (ListPreference) findPreference(getResources().getString(R.string.pref_background));
		listBackgroundGlobal.setEntries(PatternEntry.getValori(standardLayout));
		listBackgroundGlobal.setEntryValues(PatternEntry.getChiavi(standardLayout));
		listBackgroundGlobal.setDefaultValue(getPreferenceManager().getSharedPreferences().getString(getResources().getString(R.string.pref_background_theme),
				PatternEntry.primoValore()));

		ListPreference listBackgroundPa = (ListPreference) findPreference(getResources().getString(R.string.pref_background_theme_pa));
		listBackgroundPa.setEntries(PatternEntry.getValori(standardLayout));
		listBackgroundPa.setEntryValues(PatternEntry.getChiavi(standardLayout));
		listBackgroundPa.setDefaultValue(getPreferenceManager().getSharedPreferences().getString(getResources().getString(R.string.pref_background_theme),
				PatternEntry.primoValore()));

		ListPreference listBackgroundSrv = (ListPreference) findPreference(getResources().getString(R.string.pref_background_theme_srv));
		listBackgroundSrv.setEntries(PatternEntry.getValori(standardLayout));
		listBackgroundSrv.setEntryValues(PatternEntry.getChiavi(standardLayout));
		listBackgroundSrv.setDefaultValue(getPreferenceManager().getSharedPreferences().getString(getResources().getString(R.string.pref_background_theme),
				PatternEntry.primoValore()));

		ListPreference listBackground = (ListPreference) findPreference(getResources().getString(R.string.pref_background_theme));
		listBackground.setEntries(PatternEntry.getValori(standardLayout));
		listBackground.setEntryValues(PatternEntry.getChiavi(standardLayout));
		listBackground.setDefaultValue(getPreferenceManager().getSharedPreferences().getString(getResources().getString(R.string.pref_background_theme),
				PatternEntry.primoValore()));

		ListPreference listBackgroundRC = (ListPreference) findPreference(getResources().getString(R.string.pref_background_theme_rc));
		listBackgroundRC.setEntries(PatternEntry.getValori(standardLayout));
		listBackgroundRC.setEntryValues(PatternEntry.getChiavi(standardLayout));
		listBackgroundRC.setDefaultValue(getPreferenceManager().getSharedPreferences().getString(getResources().getString(R.string.pref_background_theme),
				PatternEntry.primoValore()));

		listPreferredAppScreen = (PreferenceScreen) findPreference(getResources().getString(R.string.App_preferred));
		listPreferredAppScreen.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			public boolean onPreferenceClick(Preference preference) {
				pd = ProgressDialog.show(Setup.this, null, getResources().getText(R.string.waiting), true, false);
				task = new AsyncGetInstalledApps(Setup.this, messageHandler, preference, PREFIX_PREFERRED_APPS, opclPreferedApps);
				task.execute();
				return false;
			}
		});
		listDontShowAppScreen = (PreferenceScreen) findPreference(getResources().getString(R.string.App_not_show));
		listDontShowAppScreen.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			public boolean onPreferenceClick(Preference preference) {
				pd = ProgressDialog.show(Setup.this, null, getResources().getText(R.string.waiting), true, false);
				AsyncGetInstalledApps task = new AsyncGetInstalledApps(Setup.this, messageHandler, preference);
				task.execute();
				return false;
			}
		});
		CheckBoxPreference cbShowTitleApps = (CheckBoxPreference) findPreference(getResources().getString(R.string.app_show_title));
		ListPreference lpIconDimension = (ListPreference) findPreference(getResources().getString(R.string.app_title_size));
		
		cbShowTitleApps
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

					public boolean onPreferenceChange(Preference arg0, Object arg1) {
						if ((Boolean) arg1) {
							((ListPreference) findPreference(getResources().getString(R.string.app_title_size))).setEnabled(true);
						}else{
							((ListPreference) findPreference(getResources().getString(R.string.app_title_size))).setEnabled(false);
						}
						return true;
					}

				});
		boolean showTitle = getPreferenceManager().getSharedPreferences().getBoolean(this.getResources().getString(R.string.app_show_title),false);
		if (cbShowTitleApps.isEnabled()){
			if (showTitle){
				lpIconDimension.setEnabled(true);
			}else{
				lpIconDimension.setEnabled(false);
			}
		}
		if (savedInstanceState != null) {
			task = (AsyncGetInstalledApps) savedInstanceState.get(Setup.SERIALIZABLE_TASK);
			if (task != null) {
				pd = ProgressDialog.show(Setup.this, null, getResources().getText(R.string.waiting), true, false);
				task.setMessageHandler(messageHandler);
			}
		}

		caricaDefaultHome();

	}
	private void caricaDefaultHome() {
		ListPreference homeListPreference = (ListPreference) findPreference(getResources().getString(R.string.home_click_default));
		PackageManager manager = Setup.this.getPackageManager();
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_HOME);
		final List<ResolveInfo> apps = manager.queryIntentActivityOptions(null, null, mainIntent, 0);
		if (apps != null) {
			final int count = apps.size();
			String packageName = null;
			CharSequence[] titoli = new String[count - 1];
			String[] chiavi = new String[count - 1];
			int indexHome = 0;
			for (int index = 0; index < count; index++) {
				ResolveInfo info = apps.get(index);
				packageName = info.activityInfo.applicationInfo.packageName;
				if (!packageName.equals("it.mp.multitask")) {
					titoli[indexHome] = info.loadLabel(manager);
					chiavi[indexHome] = packageName;
					indexHome++;
				}
			}
			homeListPreference.setEntries(titoli);
			homeListPreference.setEntryValues(chiavi);
		}

	}

	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (pd != null) {
			pd.dismiss();
		}
	}
}
